<template>
  <ul class="switch">
    <li class="switch-item" v-for="(item, index) in items" :key="item"
    :class="{ active: modelValue === index }"
    @click="switchItem(index)">
      <span>{{ item }}</span>
    </li>
    <div class="active-bar" ref="barRef" :style="activeStyle"></div>
  </ul>
</template>
<script>
export default {
  name: 'switches',
  props: {
    items: {
      type: Array,
      default: () => []
    },
    modelValue: {
      type: Number,
      default: 0
    }
  },
  computed: {
    activeStyle () {
      const width = this.$refs.barRef ? this.$refs.barRef.clientWidth : 120
      const x = width * this.modelValue
      return {
        transform: `translateX(${x}px)`
      }
    }
  },
  methods: {
    switchItem (index) {
      this.$emit('update:modelValue', index)
    }
  }
}
</script>
<style lang="scss" scoped>
.switch {
  display: flex;
  position: relative;
  align-items: center;
  width: 10.234542rem;
  margin: 0.6rem auto;
  border: .042644rem solid $color-highlight-background;
  border-radius: .21322rem;
  .switch-item {
    position: relative;
    z-index: 10;
    flex: 1;
    height: 1.279318rem;
    line-height: 1.279318rem;
    text-align: center;
    font-size: $font-size-medium;
    color: $color-text-d;
    &.active {
      color: $color-theme;
    }
  }
  .active-bar {
    position: absolute;
    left: 0;
    top: 0;
    width: 5.117271rem;
    height: 1.279318rem;
    transition: transform 0.3s;
    border-radius: .21322rem;
    background: $color-highlight-background;
  }
}
</style>
